package com.wangsd.common.intercepter;

import com.alibaba.fastjson.JSON;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.enums.ResultCode;
import com.wangsd.web.sys.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //本地环境直接初始化
        //if ("dev".equalsIgnoreCase(SpringUtil.getActiveProfile())) {
        //    String token = request.getHeader("x-access-token");
        //    if (StringUtils.isBlank(token)) {
        //        Cache cache = cacheManager.getCache("twoHour");
        //        cache.put(token+"weixin", "o2ke11EGrtfIAWyT5TERYhe6ZM0Q");
        //        return true;
        //    }
        //}

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,x-access-token,X-Requested-With");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");

        String token_req = request.getHeader("Access-Token");
        if (!StringUtils.isBlank(token_req)) {

            SysUser user = (SysUser) redisTemplate.opsForValue().get(token_req);

            if (user == null) {
                log.debug("请求被拦截，登录过期。");
                response.getWriter().write(JSON.toJSONString(Result.fail(ResultCode.LOGIN_EXPIRE.getCode(), ResultCode.LOGIN_EXPIRE.getMessage())));
                return false;
            }
            return true;
        } else {
            log.debug("请求被拦截，没有传token。");
            return false;
        }
    }
}
